package com.hyw.supply.controller;

import com.alibaba.fastjson2.JSONObject;
import com.hyw.supply.exception.BaseException;
import com.hyw.supply.model.Form.LoginUserForm;
import com.hyw.supply.model.vo.CommonResult;
import com.hyw.supply.model.vo.LoginUserVO;
import com.hyw.supply.model.vo.LoginVO;
import com.hyw.supply.utils.CustomToken;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

/**
 * @author zzp
 * @date 2024/3/14 11:17
 */

@RestController
@RequiredArgsConstructor
@Tag(name = "用户登录管理")
public class LoginController {


    private final AuthenticationManager authentiactionManager;

    @Operation(summary = "登录接口")
    @PostMapping("/login")
    public CommonResult<LoginVO> logingUser(@RequestBody LoginUserForm loginUserForm) {
        //登陆-调用service
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                new UsernamePasswordAuthenticationToken(loginUserForm.getUserName(), loginUserForm.getPassword());
        Authentication authenticate = authentiactionManager.authenticate(usernamePasswordAuthenticationToken);
        if (Objects.isNull(authenticate)) {
            throw new BaseException("登录失败");
        }
        LoginUserVO loginUserVO = JSONObject.parseObject(JSONObject.toJSONString(authenticate.getPrincipal()), LoginUserVO.class);
        loginUserVO.setPassword(null);

        return CommonResult.success(CustomToken.createToken(String.valueOf(loginUserVO.getId()), loginUserVO.getName(),
                loginUserVO.getAdmined(),loginUserVO.getEnterprise()));
    }
}
